package ui.fragment.group_management;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.trek2000.android.enterprise.Enterprise;
import com.trek2000.android.enterprise.R;
import com.wefika.flowlayout.FlowLayout;

import controller.company.SelectCompanyAsync;
import controller.group_management.CreateGroupAsync;
import controller.user_management.AllTabInUserManagementFragmentAsync;
import custom_view.MemberTabFrameLayout;
import ui.activity.login.Login;
import utils.Utils;

/**
 * Created by Dong Le on 6/19/2015.
 */
public class CreateGroupFragment extends Fragment implements View.OnClickListener, View.OnTouchListener{
    //Views session
    private EditText mEtGroupDescriptionInCreateGroupFragment;
    private EditText mEtGroupNameInCreateGroupFragment;
    public static FlowLayout mflowlayoutGroupManagerContentInCreateGroupFragment;
    public static FlowLayout mflowlayoutMemberContentInCreateGroupFragment;
    public static ImageButton mIbtnAddMemberToGroupManagerInCreateGroupFragment;
    private ImageButton mIbtnAddMemberToGroupInCreateGroupFragment;
    private LinearLayout mLlInCreateGroupFragment;
    public static LinearLayout mLlGroupManagerContentInCreateGroupFragment;
    public static LinearLayout mLlMemberContentInCreateGroupFragment;
    private TextView mTvCancelInCreateGroupFragment;
    private TextView mTvDoneInCreateGroupFragment;
    //the others session
    public static Context mContext;

    public static Fragment newInstance() {
        CreateGroupFragment fragment = new CreateGroupFragment();
        return fragment;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibtn_add_member_to_group_manager_in_create_group_fragment:
                //only use 1 fragment add member to group, but group manager only choose one user
                //transfer 1 parameter and set switch case
                getActivity().getSupportFragmentManager().beginTransaction().addToBackStack(null).
                        replace(R.id.fl_in_create_group_activity, AddMemberToGroupFragment.newInstance(true)
                        ).commitAllowingStateLoss();
                break;
            case R.id.ibtn_add_member_to_group_in_create_group_fragment:
                //only use 1 fragment add member to group, but member can choose many users
                //transfer 1 parameter and set switch case
                getActivity().getSupportFragmentManager().beginTransaction().addToBackStack(null).
                        replace(R.id.fl_in_create_group_activity, AddMemberToGroupFragment.newInstance(false)
                        ).commitAllowingStateLoss();
                break;
            case R.id.tv_cancel_in_create_group_fragment:
                getActivity().finish();
                break;
            case R.id.tv_done_in_create_group_fragment:
                //check date empty
                if (!"".equals(mEtGroupNameInCreateGroupFragment.getText().toString()) &&
                        !"".equals(mEtGroupDescriptionInCreateGroupFragment.getText().toString()) &&
                        Enterprise.groupManagement.getmAlPosOfItemCheckedInAddMemberToGroup() != null &&
                        Enterprise.groupManagement.getmAlPosOfItemCheckedInAddMemberToGroup().size() > 0 &&
                        Enterprise.groupManagement.getmAlPosOfItemCheckedInAddGroupManager() != null &&
                        Enterprise.groupManagement.getmAlPosOfItemCheckedInAddGroupManager().size() > 0) {
                    String MEMBER_COMPANY_IDS = "";
                    String GROUP_MANAGER = "";
                    // get member company ids
                    for (int i = 0; i < Enterprise.groupManagement.getmAlPosOfItemCheckedInAddMemberToGroup().size(); i++) {
                        MEMBER_COMPANY_IDS = MEMBER_COMPANY_IDS +
                                String.valueOf(AllTabInUserManagementFragmentAsync.mAlAllTabInUserManagement.get(
                                        Enterprise.groupManagement.getmAlPosOfItemCheckedInAddMemberToGroup().get(i)
                                ).getUserGlobalId()) + ",";
                    }
                    MEMBER_COMPANY_IDS = MEMBER_COMPANY_IDS.substring(0, MEMBER_COMPANY_IDS.length() - 1);
                    //get group manager id
                    for (int j = 0; j < Enterprise.groupManagement.getmAlPosOfItemCheckedInAddGroupManager().size(); j++) {
                        GROUP_MANAGER = GROUP_MANAGER +
                                String.valueOf(AllTabInUserManagementFragmentAsync.mAlAllTabInUserManagement.get(
                                        Enterprise.groupManagement.getmAlPosOfItemCheckedInAddGroupManager().get(j)
                                ).getUserGlobalId()) + ",";
                    }
                    GROUP_MANAGER = GROUP_MANAGER.substring(0, GROUP_MANAGER.length() - 1);
                    Log.i("","MEMBER_COMPANY_IDS " + MEMBER_COMPANY_IDS);
                    Log.i("","GROUP_MANAGER " + GROUP_MANAGER);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                        new CreateGroupAsync(getActivity()).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
                                String.valueOf(Login.user.getUserInfo().getUserGlobalId()),
                                String.valueOf(Login.user.getUserInfo().getAccessToken()),
                                String.valueOf(
                                        Enterprise.company.getCompaniesOfUserInfoSelected().getUserCompanyId()),
                                String.valueOf(
                                        Enterprise.company.getCompaniesOfUserInfoSelected().getCompanyId()),
                                String.valueOf(
                                        Enterprise.company.getCompaniesOfUserInfoSelected().getCompanyIdGroup()),
                                "add",
                                mEtGroupNameInCreateGroupFragment.getText().toString(),
                                mEtGroupDescriptionInCreateGroupFragment.getText().toString(),
                                MEMBER_COMPANY_IDS, GROUP_MANAGER);
                    else
                        new CreateGroupAsync(getActivity()).execute(
                                String.valueOf(Login.user.getUserInfo().getUserGlobalId()),
                                String.valueOf(Login.user.getUserInfo().getAccessToken()),
                                String.valueOf(
                                        Enterprise.company.getCompaniesOfUserInfoSelected().getUserCompanyId()),
                                String.valueOf(
                                        Enterprise.company.getCompaniesOfUserInfoSelected().getCompanyId()),
                                String.valueOf(
                                        Enterprise.company.getCompaniesOfUserInfoSelected().getCompanyIdGroup()),
                                "add",
                                mEtGroupNameInCreateGroupFragment.getText().toString(),
                                mEtGroupDescriptionInCreateGroupFragment.getText().toString(),
                                MEMBER_COMPANY_IDS, GROUP_MANAGER);
                } else {
                    Toast.makeText(getActivity().getApplicationContext(), R.string.toast_error_create_group, Toast.LENGTH_LONG).show();
                }

                break;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = getLayoutInflater(savedInstanceState).inflate(
                R.layout.fragment_create_group, container, false);
        initialViews(v);
        initialData();
        mContext = getActivity();
        //add member tab to create group
        checkAndAddMemberTabForGroupManagerAndMember();

        return  v;
    }

    @Override
    public boolean onTouch(View v, MotionEvent motionEvent) {
        switch (v.getId()) {
            case R.id.ll_in_create_group_fragment:
                Utils.hideSoftKeyboard(getActivity(), mEtGroupDescriptionInCreateGroupFragment);
                Utils.hideSoftKeyboard(getActivity(), mEtGroupNameInCreateGroupFragment);
                break;
        }
        return false;
    }

    private void initialData() {
        mIbtnAddMemberToGroupManagerInCreateGroupFragment.setOnClickListener(this);
        mIbtnAddMemberToGroupInCreateGroupFragment.setOnClickListener(this);
        mLlInCreateGroupFragment.setOnTouchListener(this);
        mTvCancelInCreateGroupFragment.setOnClickListener(this);
        mTvDoneInCreateGroupFragment.setOnClickListener(this);
    }

    private void initialViews(View v) {
        mEtGroupDescriptionInCreateGroupFragment = (EditText) v.findViewById(
                R.id.et_group_description_in_create_group_fragment);
        mEtGroupNameInCreateGroupFragment = (EditText) v.findViewById(
                R.id.et_group_name_in_create_group_fragment);
        mflowlayoutGroupManagerContentInCreateGroupFragment = (FlowLayout) v.findViewById(
                R.id.flowlayout_add_member_to_group_manager_in_create_group_fragment);
        mflowlayoutMemberContentInCreateGroupFragment = (FlowLayout) v.findViewById(
                R.id.flowlayout_add_member_to_group_in_create_group_fragment);
        mIbtnAddMemberToGroupManagerInCreateGroupFragment = (ImageButton) v.findViewById(
                R.id.ibtn_add_member_to_group_manager_in_create_group_fragment);
        mIbtnAddMemberToGroupInCreateGroupFragment = (ImageButton) v.findViewById(
                R.id.ibtn_add_member_to_group_in_create_group_fragment);
        mLlInCreateGroupFragment = (LinearLayout) v.findViewById(
                R.id.ll_in_create_group_fragment);
        mLlGroupManagerContentInCreateGroupFragment = (LinearLayout) v.findViewById(
                R.id.ll_group_manager_content_in_create_group_fragment);
        mLlMemberContentInCreateGroupFragment = (LinearLayout) v.findViewById(
                R.id.ll_member_content_in_create_group_fragment);
        mTvCancelInCreateGroupFragment = (TextView) v.findViewById(
                R.id.tv_cancel_in_create_group_fragment);
        mTvDoneInCreateGroupFragment = (TextView) v.findViewById(
                R.id.tv_done_in_create_group_fragment);
    }

    public static void setMemberTabForGroupManager(String avatar, int tag) {
        mLlGroupManagerContentInCreateGroupFragment.setVisibility(View.VISIBLE);
        mflowlayoutGroupManagerContentInCreateGroupFragment.addView(
                MemberTabFrameLayout.newInstance(mContext, avatar, tag));
        mflowlayoutGroupManagerContentInCreateGroupFragment.getChildAt(tag).setTag(tag);
    }

    public static void setMemberTabForMember(String avatar, int tag) {
        mLlMemberContentInCreateGroupFragment.setVisibility(View.VISIBLE);
        mflowlayoutMemberContentInCreateGroupFragment.addView(
                MemberTabFrameLayout.newInstance(mContext, avatar, tag));
        mflowlayoutMemberContentInCreateGroupFragment.getChildAt(tag).setTag(tag);
    }

    public static void removeMemberTabForGroupManger(int tag) {
        mflowlayoutGroupManagerContentInCreateGroupFragment.removeViewAt(tag);
    }

    public static void removeMemberTabForMember(int tag) {
        mflowlayoutMemberContentInCreateGroupFragment.removeViewAt(tag);
    }

    /**
     * I had a nightmare last night and i lost sleep
     * Now I'm feeling dizzy and I've got the terrible headache
     * I stay in bed most of time and I don't wanna go out
     * please drop by sometime tonight so we can hang out together
     * I can't wait to go downtown with you. It's gonna be fun.
     */
    private void checkAndAddMemberTabForGroupManagerAndMember() {
        if (Enterprise.groupManagement.getmAlPosOfItemCheckedInAddGroupManager() != null &&
                Enterprise.groupManagement.getmAlPosOfItemCheckedInAddMemberToGroup() != null) {
            Log.i("","Enterprise.groupManagement.getmAlPosOfItemCheckedInAddGroupManager().size() " +
                    Enterprise.groupManagement.getmAlPosOfItemCheckedInAddGroupManager().size());
            Log.i("","Enterprise.groupManagement.getmAlPosOfItemCheckedInAddMemberToGroup().size() " +
                    Enterprise.groupManagement.getmAlPosOfItemCheckedInAddMemberToGroup().size());
        }
        if (Enterprise.groupManagement.getmAlPosOfItemCheckedInAddGroupManager() != null &&
                Enterprise.groupManagement.getmAlPosOfItemCheckedInAddGroupManager().size() > 0 &&
                AllTabInUserManagementFragmentAsync.mAlAllTabInUserManagement.size() > 0) {
            for (int i = 0;
                 i < Enterprise.groupManagement.getmAlPosOfItemCheckedInAddGroupManager().size(); i++) {
                setMemberTabForGroupManager(
                        AllTabInUserManagementFragmentAsync.mAlAllTabInUserManagement.get(
                                Enterprise.groupManagement.getmAlPosOfItemCheckedInAddGroupManager().get(i)
                        ).getAvatar()
                        , i);
            }
        }

        if (Enterprise.groupManagement.getmAlPosOfItemCheckedInAddMemberToGroup() != null &&
                Enterprise.groupManagement.getmAlPosOfItemCheckedInAddMemberToGroup().size() >0 &&
                AllTabInUserManagementFragmentAsync.mAlAllTabInUserManagement.size() > 0) {
            for (int j = 0;
                 j < Enterprise.groupManagement.getmAlPosOfItemCheckedInAddMemberToGroup().size(); j++) {
                CreateGroupFragment.setMemberTabForMember(
                        AllTabInUserManagementFragmentAsync.mAlAllTabInUserManagement.get(
                                Enterprise.groupManagement.getmAlPosOfItemCheckedInAddMemberToGroup().get(j)
                        ).getAvatar()
                        , j);
            }
        }
        //hide ibtn add group manager after added one group manager
        if (Enterprise.groupManagement.getmAlPosOfItemCheckedInAddGroupManager() != null &&
                Enterprise.groupManagement.getmAlPosOfItemCheckedInAddGroupManager().size() > 0) {
            mIbtnAddMemberToGroupManagerInCreateGroupFragment.setVisibility(View.INVISIBLE);
        }
    }
}
